import {MutationTree} from "vuex";
import {getMachineStatus} from "@/services/liank";
import {getSettings} from "@/services/api";
import tips from "@/utils/tips";
import {State} from "@/store/state";
import {Machine, Printer, Settings, Store, LoginPayload, Location} from "@/types/mutations";
import {UserInfo} from "@/types/user";

const Mutations: MutationTree<any> = {
    updateLang(state: State, payload) {
        state.locale = payload;
    },
    async setSettings(state: State) {
        const res = await getSettings();
        const {data, code} = res
        if (code === 200) {
            state.settings = data as Settings;
        } else {
            state.settings = {} as Settings;
        }
    },
    loading(state: any, payload): void {
        state.loading = payload;
        state.loadingText = !payload || payload == true ? null : payload;
    },
    showLogin(state, payload) {
        state.showLogin = payload;
    },

    login(state: State, payload: LoginPayload): void {
        const data = payload.data;
        uni.setStorageSync("token", data.token);
        state.token = data.token;
    },
    setUserInfo(state: State, payload: { data: UserInfo }): void {
        state.userInfo = payload.data;
    },

    logout(state: any): void {
        uni.removeStorageSync('token')
        uni.removeStorageSync('userInfo')
        state.userInfo = {};
        state.isLogin = false;
    },

    foulContentModalVisible(state, payload: any) {
        state.foulContentModal = payload;
    },
    setLocation(state: State, payload: Location): void {
        state.location = payload
    },
    setPrinter(state: State, payload: Printer): void {
        state.printer = payload
    },
    setStore(state: State, payload: Store): void {
        state.store = payload
    },
    setMachine(state: State, payload: Machine): void {
        state.machine = payload
    },
    async setMachineOnline(state: State) {
        const {device_id, device_password} = state.machine
        const res = await getMachineStatus(device_id, device_password)
        if (res.code === 200) {
            state.machineOnline = res.data.info.online
        } else {
            tips.toast(res.msg)
            state.machineOnline = 0
        }
    }
};

export default Mutations;
